<?php
/**
 * Description:
 * Author: hezhizheng
 * Date: 2018/11/19
 * Time: 17:44
 * Created by Created by Panxsoft.
 */

namespace App\Models;

use App\Models\Order\Extension;
use App\Models\Order\Order;
use App\Models\Shipping\GeoZone;
use App\Services\MobileApp\AppEnv;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

/**
 * Class Setting
 * @property string type
 * @property string value
 * @property string sort_order
 * @property string code
 * @property int minimum_total
 * @property string geo_zone_id
 * @package App\Models
 * @mixin Builder
 */
class Setting extends Model
{
    const VALUE_STATUS_ON = 1;

    const CODE_CONFIG = 'config';
    const CODE_PAYMENT_ALI = 'payment_alipay';
    const CODE_PAYMENT_WECHAT = 'payment_wechat_pay';
    const CODE_PAYMENT_PAY_PAL = 'payment_pp_express';
    const CODE_PAYMENT_COD = 'payment_cod';

    const KEY_CONFIG_URL = 'config_url';
    const KEY_CONFIG_SHOW_STATUS = 'config_show_status';
    const KEY_CONFIG_NAME = 'config_name';
    const KEY_CONFIG_INVOICE_PREFIX = 'config_invoice_prefix';

    const SETTING_STATUS = '_status'; // 配置信息的状态字段
    const SETTING_SOCIALITE_APP_ID = '_app_id'; // 配置信息的app_id字段
    const SETTING_SOCIALITE_APP_SECRET = '_app_secret'; // 配置信息的app_secret字段
    const SETTING_SOCIALITE_SORT_ORDER = '_sort_order'; // 配置信息的sort_order字段
    const SETTING_SOCIALITE_ICON = '_icon'; // 配置信息的icon字段
    /**
     * APP 启动图片
     */
    const KEY_CONFIG_APP_SPLASH_IMAGE = 'config_app_splash_image';
    /**
     * 订单自动签收延时
     */
    const KEY_CONFIG_AUTO_SIGN_DELAY = 'config_order_auto_sign_delay_minute';
    /**
     * App 主题目录
     */
    const KEY_CONFIG_APP_THEME = 'config_app_theme';

    protected $guarded = [];

    protected $table = 'setting';

    public static function configNameValue()
    {
        return (new self)->where([
            ['store_id', Store::STORE_ID_DEFAULT],
            ['key', self::KEY_CONFIG_NAME],
        ])->first()->value;
    }

    public static function getStoreNameById($store_id)
    {
        return (new self)->where([
            ['store_id', $store_id],
            ['key', self::KEY_CONFIG_NAME],
        ])->first()->value ?? null;
    }

    public static function getStoreUrlById($store_id)
    {
        return (new self)->where([
                ['store_id', $store_id],
                ['key', self::KEY_CONFIG_URL],
            ])->first()->value ?? config('app.url');
    }

    public static function getStoreInvoicePrefixById($store_id)
    {
        return (new self)->where([
                ['store_id', $store_id],
                ['key', self::KEY_CONFIG_INVOICE_PREFIX],
            ])->first()->value ?? null;
    }

    /**
     * @param string $code
     * @param int $store_id
     *
     * @return array
     */
    public static function findConfigByCode(string $code,
                                            int $store_id = Store::STORE_ID_DEFAULT): array
    {
        return (new self)
            ->where(compact('store_id','code'))
            ->get(['value', 'key'])
            ->pluck('value', 'key')
            ->all();
    }

    /**
     * @param string $key
     * @param int $store_id
     *
     * @return Setting|null
     */
    public static function findConfigByKey(string $key, int $store_id = Store::STORE_ID_DEFAULT): ?self
    {
        return (new self)
            ->where(compact('key', 'store_id'))
            ->first();
    }

    /**
     * @param $prefix
     * @param array $codes
     * @param $suffix
     * @return mixed|null
     */
    public static function getValueSortOrder(array $codes, $prefix, $suffix)
    {
        $keys = array_map(function($code) use($prefix, $suffix){
            return $prefix.$code.$suffix;
        }, $codes);

        return (new self)->whereIn('key', $keys)
                ->pluck('value', 'code');
    }

    /**
     * @param $prefix
     * @param $code
     * @param $suffix
     * @param $geo_zone_id
     * @param string $total_weight
     * @return mixed|null
     * @throws \Exception
     */
    public static function getShippingTotal($prefix, $code, $suffix, $geo_zone_id, $total_weight)
    {
        if ($code === Extension::EXTENSION_SHIPPING_CODE_WEIGHT) {
            return self::getShippingWeightTotal($code, $geo_zone_id, $total_weight);
        }

        $shipping= (new self)->where('key', $prefix.$code.$suffix)
                ->where('value', $geo_zone_id)
                ->first();

        if ($shipping) {
            return (new self)->where('key', $prefix.$code.'_cost')->first()->value ?? 0;
        } else {
            return 0;
        }
    }

    /**
     * @param $code
     * @param $geo_zone_id
     * @param $total_weight
     * @return null
     * @throws \Exception
     */
    public static function getShippingWeightTotal($code, $geo_zone_id, $total_weight)
    {
        $currency = Currency::getCurrencyDefault();
        $cost_map = GeoZone::getWeightShipping($geo_zone_id, $code, $currency)['cost'];//dd($geo_zone_id, $code,$cost_map);
        $total = 0; // 默认总运费

        if ($cost_map) {
            $cost_map_weight = array_column($cost_map, 'weight');
            array_multisort($cost_map_weight,SORT_ASC, $cost_map);

            foreach($cost_map as $index => $cost)
            {
                if ($cost['weight'] >= $total_weight) {
                    $total = $cost['cost'];

                    break;
                }
            }
        }

        return $total;
    }

    /**
     * @return array|mixed
     */
    public static function getConfigShowStatus()
    {
        $setting_config_show_status = (new self)->where('code', self::CODE_CONFIG)
            ->where('key', self::KEY_CONFIG_SHOW_STATUS)
            ->first();

        return $setting_config_show_status->value ?? json_encode([]);
    }

    public static function getShippingExtensionCost($shipping_method_geo_zone_id, $code)
    {
        $shipping_extension = (new self)->where('key', Extension::SETTING_CODE_SHIPPING_PREFIX.$code.Extension::SETTING_KEY_GEO_ZONE_ID)
            ->where('value', $shipping_method_geo_zone_id)
            ->first();

        if ($shipping_extension) {
            return (new self)->where('key', Extension::SETTING_CODE_SHIPPING_PREFIX.$code.'_cost')->first()->value ?? 0;
        } else {
            return 0;
        }
    }

    /**
     * @return mixed|null|string
     */
    public static function getPayPalMode()
    {
        $value = (new self)->where('code', 'payment_pp_express')
            ->where('key', 'payment_pp_express_test')
            ->first()
            ->value ?? null;

        return $value;
    }

    /**
     * @param $payment_method
     * @return int|mixed|string
     */
    public static function getPaymentCodOrderStatusId($payment_method)
    {
        $order_status_id_default = Order::STATUS_ID_DEFAULT;

        if ($payment_method === Extension::EXTENSION_PAYMENT_COD) {
            $order_status_id_default = (new self)->where('code', 'payment_cod')
                ->where('key', 'payment_cod_order_status_id')
                ->first()
                ->value ?? Order::STATUS_ID_DEFAULT;

        }

        return $order_status_id_default;
    }

    /**
     * 根据指定的key,返回配置的值。
     *
     * @param $key
     * @return mixed|null
     */
    public static function getSettingSpecifyValue($key)
    {
        $value = (new self)->where('key', $key)
                ->where('store_id', AppEnv::storeId())
                ->first()
                ->value ?? null;

        return $value;
    }
}